package com.android.lovingpet.mine.pet;

import android.graphics.Bitmap;
import android.net.Uri;
import  android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import com.android.lovingpet.Application;
import com.android.lovingpet.bean.JsonIds;
import com.android.lovingpet.bean.Pet;
import com.android.lovingpet.common.Back;
import com.android.lovingpet.common.FileModel;
import com.android.lovingpet.util.CallbackStore;
import com.android.lovingpet.util.HttpUtil;
import com.android.lovingpet.util.ImageUtil;
import com.android.lovingpet.util.MyHttp;
import com.android.lovingpet.util.URLStore;
import com.android.lovingpet.util.Utility;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by ikata on 2018/4/29.
 */

public class PetModel {
    public void addPet(HashMap<String,String> params, Back back)
    {
        HttpUtil.postAsync(Utility.getJSessionId(), URLStore.PET_ADDFOSTER, params, new CallbackStore.CallbackId<Back>(back));
    }
    public void getPetId(HashMap<String,String> params,Back back)
    {
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.PET_GETADOPTBYMASTERID, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                back.onFailure(MyHttp.getFailureMeg());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData=response.body().string();
                int code=MyHttp.getCode(responseData);
                if (code==0)
                {
                    JsonIds jsonIds=new Gson().fromJson(responseData,JsonIds.class);
                    Bundle bundle=new Bundle();
                    bundle.putIntegerArrayList("ids",jsonIds.getIds());
                    back.onSuccess(bundle);
                }
                else
                {
                    back.onFailure(MyHttp.getCodeString(code));
                }
            }
        });
    }

    public void sortByTime(HashMap<String,String> params,Back back)
    {
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.PET_SORT_BY_TIME,params, new CallbackStore.CallbackIds<Back>(back));
    }


    public void getPetInfo(HashMap<String,String> params,Back back)
    {
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.PET_GETINFO, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                back.onFailure(MyHttp.getFailureMeg());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData=response.body().string();
                int code=MyHttp.getCode(responseData);
                if (code==0)
                {
                    try {
                        JSONObject jsonObject=new JSONObject(responseData);
                        String common = makeUpJsonString(jsonObject);

                        Pet pet=new Gson().fromJson(common,Pet.class);

                        //获取视频的第一帧赋予待领养宠物的image
                        if (pet.getVideo()!=null){
                            Bitmap bitmap= ImageUtil.getVideoThumbnail(pet.getVideo());
                            Uri uri=ImageUtil.bitmap2uri(Application.getContext(),bitmap);
                            assert uri != null;
                            pet.setImage(uri.toString());
                        }
                        getPetImage(pet);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }else{
                    back.onFailure(MyHttp.getCodeString(code));
                }

            }

            private void getPetImage(Pet pet) {
                FileModel.getInstance().downloadImage(pet.getId(), 2, new FileModel.FileBack() {
                    @Override
                    public void loadSuccess(String url) {
                        pet.setImage(url);
                        Bundle bundle=new Bundle();
                        bundle.putParcelable("result",pet);
                        back.onSuccess(bundle);
                    }

                    @Override
                    public void onFailure(String msg) {

                    }

                    @Override
                    public void onSuccess(@Nullable Bundle bundle) {

                    }
                });

            }

            @NonNull
            private String makeUpJsonString(JSONObject jsonObject) throws JSONException {
                String common=jsonObject.getJSONObject("common").toString();
                String foster = null;
                String adopt = null;
                if (jsonObject.has("foster")) {
                     foster = jsonObject.getJSONObject("foster").toString();
                }else if(jsonObject.has("adopt")){
                     adopt = jsonObject.getJSONObject("adopt").toString();
                }
                String str = null;
                if (adopt!=null){
                    str=adopt;
                }
                if (foster!=null){
                    str=foster;
                }
                common=common.substring(0,common.lastIndexOf("}"));
                assert str != null;

                //经纬度
                if (jsonObject.has("longitude")&&jsonObject.has("latitude")) {
                    str=str.substring(str.indexOf("{")+1,str.length()-1);
                    common=common+","+str;
                    String longitude = jsonObject.getString("longitude");
                    String latitude = jsonObject.getString("latitude");
                    common += ",\"longitude\":" + longitude + ",\"latitude\":" + latitude + "}";
                }else {
                    str=str.substring(str.indexOf("{")+1,str.length());
                    common=common+","+str;
                }
                return common;
            }
        });
    }
    public void deletePet(String id,Back back)
    {
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.PET_DELETE, "id", id, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData=response.body().string();
                int code=MyHttp.getCode(responseData);
                if (code==0)
                {
                    back.onSuccess(null);
                }
            }
        });
    }


}
